package com.neusoft.his.sb.util;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;


public class SecretFilter implements Filter {
	String defaultRsp = "{}";

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain)	throws ServletException, IOException {
		System.out.println("----doFilter------------------");
//		转换为HTTP协议对象
		HttpServletRequest  request =  (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
//		当前请求使用的方法
		System.out.println(request.getMethod());
		if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
//			服务器端需要响应客户端的 OPTIONS 方法请求
			response.getOutputStream().write(defaultRsp.getBytes(StandardCharsets.UTF_8));
			response.setStatus(HttpStatus.OK.value());
			response.addHeader("Access-Control-Allow-Origin", "*");
			response.addHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,PUT,DELETE");
			response.setHeader("Access-Control-Allow-Headers", "*");
			// 设置开启Cookie
			response.setHeader("Access-Control-Allow-Credentials", "true");
			System.out.println("---OPTIONS结束--------------");
			return; //必须的，允许过滤器直接对客户端进行响应
		}else {
//			如果当前请求不是OPTIONS 方法，则按既定路线前进；
			chain.doFilter(request, response);
		}
		
	}

}
